package com.wnxy.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class TokenUtil {


    private static String cookike_key = "user_token";

    //1.登录成功之后,生成包含用户账号的token,并写到cookie中,这样之后的每次请求都会带着token来访问.
    public static String createUserToken(String tokenKey, String value, HttpServletResponse response, StringRedisTemplate stringRedisTemplate){

        //生成jwtToken,并放到Cookie中去
        String token = JwtUtil.createTokenSingleInfo(30, tokenKey, value);
        CookieUtil.addCookie(response,cookike_key,token,false);

        //生成关联数据,发到redis中
        stringRedisTemplate.opsForValue().set(token,value,60, TimeUnit.MINUTES);

        return token;
    }


    // 2.从cookie里读取用户信息
    public static String getUserAccount(String tokenKey, HttpServletRequest request){

        //先从cookies中读取到token
        String tokenFromCookie = CookieUtil.getCookieValueByName(request, cookike_key);

        //从token中解析出用户account
        String account = JwtUtil.parseValueWithoutException(tokenFromCookie, tokenKey);

        return account;
    }

    //3.删除对应的cookie
    public static void deleteUserToken(HttpServletResponse response,HttpServletRequest request,StringRedisTemplate stringRedisTemplate){

        //响应返回时删除浏览器里对应的cookie
        CookieUtil.addCookie(response,cookike_key,"xxxx",true);

        //删除关联数据
        String tokenFromCookie = CookieUtil.getCookieValueByName(request, cookike_key);
        stringRedisTemplate.delete(tokenFromCookie);

    }




}
